/**
 * 
 */
package com.acxiom.bsh.service.impl;

import java.net.URLDecoder;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.acxiom.bsh.constants.ThreadLocalContextHolder;
import com.acxiom.bsh.dao.CommoDao;
import com.acxiom.bsh.dao.SigninDao;
import com.acxiom.bsh.entity.QuerySigninResult;
import com.acxiom.bsh.entity.SigninResult;
import com.acxiom.bsh.logger.LoggerManager;
import com.acxiom.bsh.request.PointRequest;
import com.acxiom.bsh.response.ApiResponse;
import com.acxiom.bsh.service.ApiService;
import com.acxiom.bsh.service.SigninService;

/**
 * @author luciyu
 *
 */
@Service
public class SigninServiceImpl implements SigninService {

	@Autowired
	private SigninDao signinDao;

	@Autowired
	private CommoDao commonDao;

	@Autowired
	ApiService apiService;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public SigninResult signin(String mixNick) {

		SigninResult result = new SigninResult();
		result.setSuccess(true);
		try {
			String sellerName = URLDecoder.decode(ThreadLocalContextHolder.get().getValue(), "UTF-8");

			signinDao.signin(mixNick, sellerName);
		} catch (Exception e) {
			LoggerManager.getCommonLogger().error(e.getMessage());
			result.setSuccess(false);
			result.setCode("099");
			result.setMessage("系统繁忙，请稍后再试");
			return result;
		}

		String pointCode = commonDao.getSparameter("SIGNIN_POINT_CODE");

		PointRequest request = new PointRequest();
		request.setEventCode(pointCode);
		request.setMix_taobaoId(mixNick);
		request.setiSN(System.currentTimeMillis());
		request.setEventMemo("signin add Points");

		ApiResponse response = apiService.post("point", request);
		if (response == null || !response.getMeta().isSuccess()) {
			result.setSuccess(false);
			result.setCode("099");
			result.setMessage("系统繁忙，请稍后再试");
		}

		return result;
	}

	@Override
	public QuerySigninResult querySignin(String mixNick) {

		QuerySigninResult result = new QuerySigninResult();
		result.setSuccess(true);
		List<Integer> list = null;
		try {
			list = signinDao.querySignin(mixNick);
		} catch (Exception e) {
			LoggerManager.getCommonLogger().error(e.getMessage());
			result.setSuccess(false);
			result.setCode("099");
			result.setMessage("系统繁忙，请稍后再试");
			return result;
		}

		result.setSiginDateList(list);

		return result;
	}

}
